package cn.itcast.nems.order.service.impl;

import cn.itcast.nems.order.dao.dataobject.OrderLineDO;
import cn.itcast.nems.order.dao.entity.OrderLine;
import cn.itcast.nems.order.dao.mapper.OrderLineMapper;
import cn.itcast.nems.order.dto.OrderLineDTO;
import cn.itcast.nems.order.service.OrderLineService;
import cn.itcast.nems.product.api.ProductApi;
import cn.itcast.nems.product.dto.ProductDTO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 销售订单-行 服务实现类
 * </p>
 *
 * @author liyong
 * @since 2023-08-31
 */
@Service
public class OrderLineServiceImpl extends ServiceImpl<OrderLineMapper, OrderLine> implements OrderLineService {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private final OrderLineMapper orderLineMapper;
    private final ProductApi productApi;

    public OrderLineServiceImpl(OrderLineMapper orderLineMapper,
                                ProductApi productApi) {
        this.orderLineMapper = orderLineMapper;
        this.productApi = productApi;
    }

    @Override
    public void addOrderLine(List<OrderLineDTO> orderLineDTOs) {
        if (orderLineDTOs == null || orderLineDTOs.isEmpty()) {
            logger.warn("订单行为空");
            return;
        }
        orderLineDTOs.forEach(line -> {
            final ProductDTO product = productApi.getProduct(line.getProductId());
            line.copyProductProperties(product);
            OrderLine ol = new OrderLine();
            BeanUtils.copyProperties(line, ol);
            if (ol.getQuantity() == null) {
                ol.setQuantity((byte) 1);
            }
            ol.setOriginalAmount(ol.getPrice() * ol.getQuantity());
            int amountDue = ol.getOriginalAmount();
            if (ol.getDiscountAmount() != null) {
                amountDue -= ol.getDiscountAmount();
            }
            ol.setAmountDue(amountDue);
            this.orderLineMapper.insert(ol);
        });
    }

    @Override
    public List<Map<String, Object>> listOrderLine(String orderId) {
        return orderLineMapper.listOrderLine(orderId);
    }

    @Override
    public List<OrderLineDO> findByIdAndState(OrderLineDO orderLineDO) {
        return getBaseMapper().findByIdAndState(orderLineDO);
    }
}
